package com.wootion.cims.general.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.bcel.internal.generic.DADD;
import com.wootion.cims.dao.PersonDao;
import com.wootion.cims.dao.PersonInputDao;
import com.wootion.cims.general.enumtype.UseString;
import com.wootion.cims.module.communitypersonal.model.Person;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/***
 *
 * 监听器
 *
 ***/

@Data
@Slf4j
@Component
public class EasyExcelOrderListener extends AnalysisEventListener<ExcelOrder> {

    List<JSONObject> slist = new ArrayList<>();

    List<ExcelOrder> elist = new ArrayList<>();

    List<Person> people = new ArrayList<>();

    Integer i = 1;

    Integer cout = 0;

    @Resource
    private ChackUtil chackUtil;

    @Resource
    private PersonDao personDao;

    @Resource
    private PersonInputDao personInputDao;

    /**
     * 此方法每一条数据解析都会来调用
     *
     * @param data
     * @param context
     */
    @SneakyThrows
    @Override
    public void invoke(ExcelOrder data, AnalysisContext context) {
        String communityId = BaseContext.getLocalCommunityId();
        String plotId = BaseContext.getLocalPlotId();
        String abode = BaseContext.getLocalAbode();
        BaseContext.removeCommunityId();
        BaseContext.removePlotId();
        BaseContext.removePlotId();
        boolean istrue = true;
        List<String> list = new ArrayList<>();
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(data));
        Field[] declaredFields = ExcelOrder.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
            String[] value = annotation.value();
            for (String s : value) {
                String string = jsonObject.getString(declaredField.getName());
                if (s.equals("身份证号") || s.equals("姓名") || s.equals("民族") || s.equals("手机号")){
                    if (!Optional.ofNullable(string).isPresent() ){
                        list.add(s+"不允许为空");
                        istrue = false;
                        continue;
                    }
                }
                if (Optional.ofNullable(string).isPresent() ){
                    if (string.length()>=500){
                        list.add(s+"超出字数限制");
                        continue;
                    }
                }

                if (!Optional.ofNullable(string).isPresent() ){

                }else {
                        String s1 = chackUtil.dataChack(string, s,communityId,plotId,abode);
                        if (Optional.ofNullable(s1).isPresent()) {
                            list.add(s1);
                            istrue = false;
                        }
                }
            }
        }

        if (istrue){
//            JSONObject jsonObject1 = new JSONObject();
            String string = JSONObject.toJSONString(data);
            JSONObject jsonObject2 = JSONObject.parseObject(string);
            Person person = jsonObject2.toJavaObject(Person.class);
            String tradeName = person.getTradeName();
            if(StringUtils.hasText(tradeName)){
                if(abode.equals("辖区外")){
                    if(tradeName.contains("-")){
                        String[] split = tradeName.split("-");
                        if(split.length == 2){
                            person.setOut2Province(split[0]);
                            person.setOut2City(split[1]);
                        }
                        if(split.length == 3){
                            person.setOut2Province(split[0]);
                            person.setOut2City(split[1]);
                            person.setOut2FullAddress(split[2]);
                        }
                    }else {
                        person.setOut2Province(tradeName);
                    }
                }
            }




            //根据身份证号设置年龄,出生日期,性别
            int ageFromIdCard = IdCardNumberUtils.getAgeFromIdCard(data.getIdNumber());
            String birthDayFromIdCard = IdCardNumberUtils.getBirthDayFromIdCard(data.getIdNumber());
            Object sex_by_string = IdCardNumberUtils.getSexFromIdCard(data.getIdNumber()).get("sex_by_string");

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = null;
            try {
                parse = simpleDateFormat.parse(birthDayFromIdCard);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            person.setAge(ageFromIdCard+"");
            if (Optional.ofNullable(sex_by_string).isPresent()){
                person.setGender(sex_by_string.toString());
            }
            person.setBirthTime(parse);

            person.setEnabled(false).setDrInset("0");
            String[] split = {};
            if (Optional.ofNullable(data.getZhxi()).isPresent()) {
                split = data.getZhxi().split("、");
            }
            List<String> list1 = new ArrayList<>();

            for (String s : split) {
                list1.add(s);
            }

            if (list1.contains("老年人")) {
                person.setOldman(UseString.老年人_存在.getString());
            }else {
                person.setOldman(UseString.老年人_不存在.getString());
            }

            if (list1.contains("优抚")) {
                person.setCareMan(UseString.优抚_存在.getString());
            }else {
                person.setCareMan(UseString.优抚_不存在.getString());
            }

            if (list1.contains("残疾人")) {
                person.setDeformedMan(UseString.残疾人_存在.getString());
            }else {
                person.setDeformedMan(UseString.残疾人_不存在.getString());
            }

            if (list1.contains("低保")) {
                person.setUnderProtect(UseString.低保_存在.getString());
            }else {
                person.setUnderProtect(UseString.低保_不存在.getString());
            }

            if (list1.contains("党员")) {
                person.setPartMan(UseString.党员_存在.getString());
            }else {
                person.setPartMan(UseString.党员_不存在.getString());
            }

            if (list1.contains("租户")) {
                person.setTenant(UseString.租户_存在.getString());
            }else {
                person.setTenant(UseString.租户_不存在.getString());
            }

            person = mark(person);

            if (Optional.ofNullable(person.getCrowd()).isPresent()){
                String[] split1 = person.getCrowd().split("、");
                List<String> list2 = new ArrayList<>();

                for (String s : split1) {
                    list2.add(s);
                }
                person.setCrowd(JSONObject.toJSONString(list2));
            }


            if (Optional.ofNullable(person.getHealthState()).isPresent()) {
                String[] split2 = person.getHealthState().split("、");
                List<String> list3 = new ArrayList<>();

                for (String s : split2) {
                    list3.add(s);
                }
                person.setHealthState(JSONObject.toJSONString(list3));
            }


            String s = chackUtil.checkResidence(abode,communityId, plotId, data.getTradeName());
            if (Optional.ofNullable(s).isPresent()){
                person.setAbodeId(s);
            }
            personDao.insert(person);
            people.add(person);
        }else {
            StringBuilder stringBuilder = null;
            for (String s : list) {

                if (Optional.ofNullable(stringBuilder).isPresent()){
                    stringBuilder.append(","+s);
                }else {
                    stringBuilder = new StringBuilder(s);
                }
            }
            data.setWrongPart(stringBuilder.toString());
            elist.add(data);
        }

        if (!list.isEmpty()){
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("hs",i);
            jsonObject1.put("list",list);
            slist.add(jsonObject1);
        }
        i++;
        System.out.println("解析到一条数据："+data);
//        for (ExcelOrder excelOrder : list) {
//            System.out.println("e" +excelOrder);
//        }
    }

    /**
     * 所有数据解析完成都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("所有数据解析完成！！！");
    }

    private Person mark(Person person) {
        JSONObject jsonObject = JSONObject.parseObject(person.getOldman());
        boolean enable = jsonObject.getBoolean("enable");
        if (enable) {
            person.setOldmanInset("true");
        } else {
            person.setOldmanInset("false");
        }

        jsonObject = JSONObject.parseObject(person.getCareMan());
        enable = jsonObject.getBoolean("enable");
        if (enable) {
            person.setCareInset("true");
        } else {
            person.setCareInset("false");
        }

        jsonObject = JSONObject.parseObject(person.getPartMan());
        enable = jsonObject.getBoolean("enable");
        if (enable) {
            person.setPartInset("true");
        } else {
            person.setPartInset("false");
        }

        jsonObject = JSONObject.parseObject(person.getUnderProtect());
        enable = jsonObject.getBoolean("enable");
        if (enable) {
            person.setUnderInset("true");
        } else {
            person.setUnderInset("false");
        }

        jsonObject = JSONObject.parseObject(person.getDeformedMan());
        enable = jsonObject.getBoolean("enable");
        if (enable) {
            person.setDeforInset("true");
        } else {
            person.setDeforInset("false");
        }

        jsonObject = JSONObject.parseObject(person.getTenant());
        enable = jsonObject.getBoolean("enable");
        if (enable) {
            person.setTentInset("true");
            person.setLivehold("租赁");
        } else {
            person.setTentInset("false");
        }

        return person;
    }


    private boolean CheckIdNumber(String string){
        //根据身份证号设置年龄,出生日期,性别
        int ageFromIdCard = IdCardNumberUtils.getAgeFromIdCard(string);
        String birthDayFromIdCard = IdCardNumberUtils.getBirthDayFromIdCard(string);
        Object sex_by_string = IdCardNumberUtils.getSexFromIdCard(string).get("sex_by_string");

        if (!Optional.ofNullable(birthDayFromIdCard).isPresent() || ageFromIdCard ==0 || !Optional.ofNullable(sex_by_string).isPresent()){
            return false;
        }else {
            return true;
        }
    }
}